<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace backend\controllers;

use builder\base\BaseController;
use builder\helper\App;
use builder\helper\H5;
use builder\helper\T;
use builder\table\TableBuilder;
use common\models\Admin;
use common\models\EmailRecord;
use common\models\SmsRecord;

/**
 * 短信和邮件记录
 * @author cleverstone
 * @since ym2.0
 */
class RecordController extends BaseController
{
    public $actionVerbs = [
        'sms' => ['GET'],
        'sms-content' => ['GET'],
        'sms-delete' => ['POST'],
        'email' => ['GET'],
        'email-content' => ['GET'],
        'email-delete' => ['POST'],
    ];

    /**
     * 短信记录
     * @return string
     * @throws \Throwable
     */
    public function actionSms()
    {
        $userColumns = Admin::query(['username'])->indexBy('id')->column();
        $userColumns[0] = Admin::SYSTEM_NAME;
        ksort($userColumns);

        $table = TableBuilder::instance(['id' => 'Record_Sms']);

        if ($this->isAjax) {
            $table->setColumnDependency($userColumns)
                ->setQuery(function () {
                    $query = SmsRecord::query();

                    $params = $this->filteredGet;
                    [$startAt, $endAt] = T::rangeDateSplit($params['created_at'] ?? null);

                    $keywordWhere = [];
                    if (isset($params['keyword']) && $params['keyword'] !== '') {
                        switch ($params['k_type']) {
                            case 'category':
                                $keywordWhere = ['like', 'category', $params['keyword']];
                                break;
                            case 'receive_mobile':
                                $keywordWhere = ['like', 'receive_mobile', $params['keyword']];
                                break;
                            case 'content':
                                $keywordWhere = ['like', 'content', $params['keyword']];
                                break;
                        }
                    }

                    $query->andFilterWhere([
                        'and',
                        $keywordWhere,
                        ['sender' => $params['sender'] ?? null],
                        ['between', 'created_at', $startAt, $endAt],
                    ]);

                    return $query;
                })
                ->setOrderBy(['created_at' => SORT_DESC])
                ->setColumns([
                    'id',
                    'category',
                    'Code_Str' => function ($row) {
                        return $row['code'] ?: '-';
                    },
                    'Sender_Str' => function ($row, $dependency) {
                        return !empty($dependency[$row['sender']]) ? $dependency[$row['sender']] : '-';
                    },
                    'receive_mobile',
                    'created_at',
                ]);
        } else {
            $t = date('t');
            App::setViewBreadcrumb([
                ['name' => '日志/记录'],
                ['name' => '短信记录', 'url' => 'record/sms'],
            ]);

            $startAt = T::dayToAbsoluteDate(-30, false, true);
            $endAt = date('Y-m-d 23:59:59');
            $table->setTitle('短信记录')
                ->setTableHead([
                    $this->tableHead->field('id')->title('ID'),
                    $this->tableHead->field('category')->title('短信种类')->minWidth(150),
                    $this->tableHead->field('Code_Str')->title('校验码')->minWidth(150),
                    $this->tableHead->field('Sender_Str')->title('发送人')->minWidth(150),
                    $this->tableHead->field('receive_mobile')->title('接收人')->minWidth(150),
                    $this->tableHead->field('created_at')->title('发送时间')->minWidth(150),
                    $this->tableHead->toolbar()->title('操作项')->fixedNone()->width(120),
                ])
                ->setRowOperation([
                    $this->rowOperation->modal('短信详情')->title('查 看')->route('record/sms-content')->width(560)->height(400)->closeBtn(),
                ])
                ->setToolbarCustom([
                    $this->toolbarCustom->ajax()->title('删除半年前短信')->route('record/sms-delete')->btnClass('layui-btn-danger')->method('post'),
                ])
                ->setToolbarFilter([
                    'created_at' => $this->toolbarFilter->datetime()->label('发送日期')->placeholder('请选择')->defaultValue("$startAt / $endAt")->uiClass('w-auto float-none')->style('width:280px;')->quickChoice(['昨日' => T::createRangeDate('-1 day', '-1 day'), '近3日' => T::createRangeDate('-2 days'), '近7日' => T::createRangeDate('-6 days'), '近'.$t.'日' => T::createRangeDate('-'.($t-1).' days')]),
                    'sender' => $this->toolbarFilter->select()->label('发送人')->placeholder('请选择')->options($userColumns)->uiClass('w-md-350'),
                    'k_type' => $this->toolbarFilter->select()->label(null)->options(['category' => '短信种类', 'receive_mobile' => '接收手机号', 'content' => '短信内容'])->uiConfig('width', '100px')->uiClass('w-100px')->style(['margin-right' => '-10px'])->uiConfig('allowClear', false)->defaultValue('category'),
                    'keyword' => $this->toolbarFilter->text()->label(null)->placeholder('短信种类/接收手机号/短信内容')->uiClass('w-280'),
                ])
                ->setColumnFilter()
                ->setToolbarRefresh();
        }

        return $table->render();
    }

    /**
     * 查看短信内容
     * @param int $id 短信记录ID
     * @return string
     * @throws \Throwable
     */
    public function actionSmsContent($id)
    {
        $detail = SmsRecord::query(['content'])->where(['id' => $id])->one();
        if (empty($detail['content'])) {
            return $this->renderContentX(
                $this->renderFile('@app/views/public/empty/index.php', [
                    'blockHeight' => '180px',
                    'message' => '嘿嘿，短信是空的！你没想到吧。'
                ])
            );
        }

        return $this->renderContentX(
            H5::text($detail['content'], [
                'class' => 'p-5 f15',
            ], 'p')
        );
    }

    /**
     * 删除五个月前的短信记录
     * @return \yii\web\Response
     */
    public function actionSmsDelete()
    {
        $lastFive = date('Y-m-d H:i:s', strtotime('-5 months'));
        $result = SmsRecord::deleteAll(['<=', 'created_at', $lastFive]);
        if ($result) {
            return $this->asOk('删除半年前【短信记录】成功，删除数量：' . $result . '条。');
        }

        return $this->asOk('半年前【短信记录】为空，不需要删除。');
    }

    /**
     * 邮件记录
     * @return string
     * @throws \Throwable
     */
    public function actionEmail()
    {
        $userColumns = Admin::query(['username'])->indexBy('id')->column();
        $userColumns[0] = Admin::SYSTEM_NAME;
        ksort($userColumns);

        $table = TableBuilder::instance(['id' => 'Record_Email']);

        if ($this->isAjax) {
            $table->setColumnDependency($userColumns)
                ->setQuery(function () {
                    $query = EmailRecord::query();

                    $params = $this->filteredGet;
                    [$startAt, $endAt] = T::rangeDateSplit($params['created_at'] ?? null);

                    $keywordWhere = [];
                    if (isset($params['keyword']) && $params['keyword'] !== '') {
                        switch ($params['k_type']) {
                            case 'category':
                                $keywordWhere = ['like', 'category', $params['keyword']];
                                break;
                            case 'receive_email':
                                $keywordWhere = ['like', 'receive_email', $params['keyword']];
                                break;
                            case 'content':
                                $keywordWhere = ['like', 'content', $params['keyword']];
                                break;
                        }
                    }
                    
                    $query->andFilterWhere([
                        'and',
                        $keywordWhere,
                        ['sender' => $params['sender'] ?? null],
                        ['between', 'created_at', $startAt, $endAt],
                    ]);

                    return $query;
                })
                ->setOrderBy(['created_at' => SORT_DESC])
                ->setColumns([
                    'id',
                    'category',
                    'Code_Str' => function ($row) {
                        return $row['code'] ?: '-';
                    },
                    'Sender_Str' => function ($row, $dependency) {
                        return !empty($dependency[$row['sender']]) ? $dependency[$row['sender']] : '-';
                    },
                    'receive_email',
                    'created_at',
                ]);
        } else {
            $t = date('t');
            App::setViewBreadcrumb([
                ['name' => '日志/记录'],
                ['name' => '邮件记录', 'url' => 'record/email'],
            ]);

            $startAt = T::dayToAbsoluteDate(-30, false, true);
            $endAt = date('Y-m-d 23:59:59');
            $table->setTitle('邮件记录')
                ->setTableHead([
                    $this->tableHead->field('id')->title('ID'),
                    $this->tableHead->field('category')->title('邮件种类')->minWidth(150),
                    $this->tableHead->field('Code_Str')->title('校验码')->minWidth(150),
                    $this->tableHead->field('Sender_Str')->title('发送人')->minWidth(150),
                    $this->tableHead->field('receive_email')->title('接收邮箱')->minWidth(150),
                    $this->tableHead->field('created_at')->title('发送时间')->minWidth(150),
                    $this->tableHead->toolbar()->title('操作项')->fixedNone()->width(120),
                ])
                ->setRowOperation([
                    $this->rowOperation->page()->title('查 看')->route('record/email-content')->targetBlank(),
                ])
                ->setToolbarCustom([
                    $this->toolbarCustom->ajax()->title('删除半年前邮件')->route('record/email-delete')->btnClass('layui-btn-danger')->method('post'),
                ])
                ->setToolbarFilter([
                    'created_at' => $this->toolbarFilter->datetime()->label('发送日期')->placeholder('请选择')->defaultValue("$startAt / $endAt")->uiClass('w-auto float-none')->style('width:280px;')->quickChoice(['昨日' => T::createRangeDate('-1 day', '-1 day'), '近3日' => T::createRangeDate('-2 days'), '近7日' => T::createRangeDate('-6 days'), '近'.$t.'日' => T::createRangeDate('-'.($t-1).' days')]),
                    'sender' => $this->toolbarFilter->select()->label('发送人')->placeholder('请选择')->options($userColumns)->uiClass('w-md-350'),
                    'k_type' => $this->toolbarFilter->select()->label(null)->options(['category' => '邮件种类', 'receive_email' => '接收邮箱', 'content' => '短信内容'])->uiConfig('width', '100px')->uiClass('w-100px')->style(['margin-right' => '-10px'])->uiConfig('allowClear', false)->defaultValue('category'),
                    'keyword' => $this->toolbarFilter->text()->label(null)->placeholder('邮件种类/接收邮箱/短信内容')->uiClass('w-280'),
                ])
                ->setColumnFilter()
                ->setToolbarRefresh();
        }

        return $table->render();
    }

    /**
     * 查看邮件内容
     * @param int $id 邮件记录ID
     * @return string
     * @throws \Throwable
     */
    public function actionEmailContent($id)
    {
        $detail = EmailRecord::query(['content'])->where(['id' => $id])->one();
        if (empty($detail['content'])) {
            return $this->renderContentX(
                $this->renderFile('@app/views/public/empty/index.php', [
                    'blockHeight' => '180px',
                    'message' => '嘿嘿，邮件是空的！你没想到吧~~'
                ])
            );
        }

        return $detail['content'];
    }

    /**
     * 删除五个月前的邮件记录
     * @return \yii\web\Response
     */
    public function actionEmailDelete()
    {
        $lastFive = date('Y-m-d H:i:s', strtotime('-5 months'));
        $result = EmailRecord::deleteAll(['<=', 'created_at', $lastFive]);
        if ($result) {
            return $this->asOk('删除半年前【邮件记录】成功，删除数量：' . $result . '条。');
        }

        return $this->asOk('半年前【邮件记录】为空，不需要删除。');
    }
}